package com.wzw.conference.service;

import com.wzw.conference.entity.Talk;
import com.wzw.conference.exception.ConferenceException;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import lombok.NonNull;
import org.apache.commons.lang3.StringUtils;

/**
 *
 * @author wzw
 * @date 2023/3/29
 */
public class TalkService {


  public List<Talk> stringToTalk(List<String> list) {

    return list.stream()
        .map(str -> str.endsWith("lightning") ? str.replace("lightning", "5min") : str)
        .filter(str -> titleNotHaveDigit(parseTalkTitle(str))
            && judgeTalkTimeFormat(talkTime(str))
            && judgeTalkTimeDuration(talkTimeDuration(str)))
        .map(str -> new Talk(parseTalkTitle(str), talkTimeDuration(str)))
        .collect(Collectors.toList());
  }

  private Integer talkTimeDuration(String str) {
    return Integer.parseInt(str.substring(str.lastIndexOf(" ") + 1).replace("min", "").trim());
  }

  private String talkTime(String str) {
    return str.substring(str.lastIndexOf(" ") + 1);
  }

  private String parseTalkTitle(String str) {
    return str.substring(0, str.lastIndexOf(" "));
  }


  public boolean titleNotHaveDigit(@NonNull String title) {
    Optional.ofNullable(title).filter(t -> !StringUtils.isBlank(t))
        .orElseThrow(() -> new ConferenceException("标题不能为空"));
    boolean haveDigit = title.matches(".*\\d.*");
    if (haveDigit) {
      throw new ConferenceException("标题不能有数字");
    }
    return true;
  }


  public boolean judgeTalkTimeFormat(String talkTime) {
    String regx = "^[1-9]+\\d*min$";
    if (!talkTime.matches(regx)) {
      throw new ConferenceException("时间格式不符合要求");
    }
    return true;
  }


  public boolean judgeTalkTimeDuration(Integer time) {
    int maxTime = 240;
    if (time > maxTime) {
      throw new ConferenceException("会议时间过长");
    }
    return true;
  }

  public List<Talk> sortTalkByDuration(List<Talk> allTalks) {
    allTalks.sort(Collections.reverseOrder());
    return allTalks;
  }


}
